<?php
include_once( 'YDB.php' );
class L
{
	public static $LOG_TABLE = 'logs';
	private static $VAR_OPTIONS = array(
		'_GET'     => false,
		'_POST'    => false,
		'_REQUEST' => false,
		'_SESSION' => false,
		'_COOKIE'  => false,
		'_SERVER'  => false,
	);

	/**
	 * Logs superglobal variables.
	 * @param array $params options to control which superglobal variables to log.
	 */
	public static function vars( array $params = [ ] )
	{
		$var_options = array_merge( self::$VAR_OPTIONS, $params );
		foreach ( $var_options as $optkey => $optval )
		{
			if ( array_key_exists( $optkey, self::$VAR_OPTIONS ) && $optval )
			{
				switch ( $optkey )
				{
					case '_GET':
						self::log( $_GET, '_GET' );
						break;
					case '_POST':
						self::log( $_POST, '_POST' );
						break;
					case '_REQUEST':
						self::log( $_REQUEST, '_REQUEST' );
						break;
					case '_SESSION':
						self::log( isset( $_SESSION ) ? $_SESSION : [ ], '_SESSION' );
						break;
					case '_COOKIE':
						self::log( $_COOKIE, '_COOKIE' );
						break;
					case'_SERVER':
						self::log( $_SERVER, '_SERVER' );
						break;
				}
			}
		}
	}

	/**
	 * Logs content into DB.
	 * @param mixed  $value content to log
	 * @param string $title title or description of log entry
	 */
	public static function log( $value, $title = 'main' )
	{
		$sql  = "INSERT INTO " . self::$LOG_TABLE . " SET log_time=:log_time, log_text=:log_text, log_title=:log_title";
		$stmt = DB::conn()->prepare( $sql );
		$stmt->execute( array(
			':log_time'  => date( 'Y-m-d H:i:s', time() ),
			':log_text'  => print_r( $value, true ),
			':log_title' => $title,
		) );
		//		DB::conn()->exec( sprintf( "INSERT INTO %s SET log_time='%s', log_text='%s', log_title='%s'",
		//			self::$LOG_TABLE, date( 'Y-m-d H:i:s', time() ), print_r( $value, true ), $title ) );
	}
}